<template>
  <div v-loading="loading">
    <cus-form ref="formRef" :nodes="nodes" :width="files ? '422px' : '500px'" />
    <el-upload
      drag
      :action="action"
      :file-list="fileList"
      multiple
      ref="uploadRef"
      :on-success="uploadSuccess"
      :on-remove="fileRemove"
      v-if="type"
    >
      <div class="upload-content">
        <i class="el-icon-upload" />
        <div>将文件拖到此处，或<span>点击上传</span></div>
        <p>
          <span>支持扩展名：</span
          ><i v-for="i in acceptFormat" :key="i">{{ i }}、</i>
        </p>
      </div>
    </el-upload>
  </div>
</template>
<script lang="ts">
import { ref, Ref, PropType } from 'vue';
import $ from '$';
import { useStore } from 'vuex';
import SelectedTopicComponent from '@/views/test-paper/components/selected-topic.vue';
import { ElMessage } from 'element-plus'

export default {
  props: {
    files: {
      type: Array,
      default: () => ([])
    },
    paperType: Number || undefined,
    type: Number,
    plan: Boolean,
    addPaper: Function as PropType<(id) => void>,
  },
  setup(props) {
    let loading = ref(true)
    let action = `${import.meta.env.VITE_APP_BASE_URL}/system/file/uploadFile`;
    let acceptFormat = ['pdf', 'doc', 'docx', 'pptx']

    let store = useStore();
    let formRef = ref();

    let userId = store.getters.userInfo.user.id;

    let subjectDefault = [store.getters.subject.parentCode, store.getters.subject.code];
    let titleDefault = props.files.map((item: any) => {
      let ids: any[] = []
      ids.push(item.name)
      return ids.join(',')
    })
    let nodes: Ref<any[]> = ref([
      {
        label: "练习名称",
        key: "title",
        type: "input",
        default: titleDefault,
        rule: { required: true, message: "请输入练习名称" },
      },
      {
        label: "分类",
        key: "exerciseType",
        type: "select",
        options: [ { name: '进门测', id: 1 }, { name: '过手练', id: 2 }, { name: '出门测', id: 3 }, { name: '课堂巩固', id: 4 } ],
        rule: { required: true, message: "请选择分类" },
      },
      {
        label: "年级",
        key: "gradeId",
        type: "select",
        options: [],
        rule: { required: true, message: "请选择级" },
      },
      {
        label: "教材",
        key: "teacherBookVersionId",
        type: "select",
        options: [],
        rule: { required: true, message: "请选择教材版本" },
      },
      {
        label: '班型',
        key: 'courseTypeId',
        type: 'select',
        rule: { required: true, message: "请选择班型" },
      },
      {
        label: '总分',
        key: 'totalScore',
        type: props.type ? 'number' : 'hidden',
        min: 0,
        rule: { required: true, message: "请填写总分" },
      },
      {
        label: '学期',
        key: 'season',
        type: 'select',
        options: [],
        rule: { required: true, message: "请选择学期" },
      },
      {
        label: '年份',
        key: 'year',
        type: 'select',
        options: [],
        rule: { required: true, message: "请选择年份" },
      },
    ]);
    let subjectChange = (val) => {
      $.http.post('/permission/user/userDataRules', { userId, subjectCode: val[1] }).then((res: any) => {
        nodes.value[2].options = res.json.grades;
        nodes.value[3].options = res.json.bookVersions;
        nodes.value[4].options = res.json.courseTypes;
        nodes.value[6].options = res.json.terms;
        nodes.value[7].options = res.json.years;
      })
    }
    subjectChange(subjectDefault);

    let fileList: Ref<any[]> = ref([]);
    Promise.all(props.files.map((file: any) => {
      let formdata = new FormData();
      formdata.append('file', file);
      return $.http.upload('/system/file/uploadFile', formdata);
    })).then((list: any[]) => {
      loading.value = false
      fileList.value = list.map(res => ({ ...res.json, name: res.json.oriFilename, url: res.json.filePath }))
    });
    const uploadSuccess = (res) => {
      fileList.value.push({ ...res.json, name: res.json.oriFilename, url: res.json.filePath });
    };
    const fileRemove = (file) => {
      fileList.value.splice(fileList.value.findIndex(f => file.filePath === f.filePath), 1);
    };
    const save = (resolve, reject) => {
      formRef.value.validate(valid => {
        if (valid) {
          let data = {
            ...valid,
            paperType: props.paperType ,
            subjectId: subjectDefault[1],
            isExercise: 1, //1 同步练习 0 或不传试卷
          }
          if (!props.paperType) {
            if (fileList.value.length < 1) { reject(ElMessage.warning('请上传文件！')); return; }
            $.http.json('/tiku/paper/batchSavePaper', { ...data, papers: fileList.value }).then(res => {
              if (res.result) {
                ElMessage.success('上传试卷成功~！');
                resolve(true)
                $.emitter.emit('add-test-success');
              } else {
                ElMessage.warning(res.msg);
                reject()
              }
            })
          } else {
            $.drawer.create({
              title: '选择试题',
              closable: false,
              zIndex: 2200,
              width: 'calc(100% - 200px)',
              component: SelectedTopicComponent,
              props: { data, isExercise: 1}
            }).then(res => {
              resolve();
              !props.plan && $.emitter.emit('add-test-success', res);
              if (props.addPaper) {
                props.plan && props.addPaper(res)
              }
            } ).catch(err => reject());
          }
        } else {
          reject();
        }
      });
    };

    return { nodes, save, formRef, fileList, acceptFormat, action, uploadSuccess, fileRemove, loading };
  },
};
</script>
<style lang="scss" scoped>
:deep(.el-upload) {
  width: 100%;
  .el-upload-dragger {
    width: 100%;
    height: 160px;
    background: none;
  }
}
.file-upload-content {
  padding: 20px 70px;
  background: #ebf0fc;
  border: 1px solid #ebf0fc;
  border-radius: 4px;
}
.upload-content {
  i {
    margin-top: 24px;
    color: #72b22a;
  }
  div {
    color: #1a2633;
    margin-bottom: 8px;
    span {
      color: #72b22a;
    }
  }
  p {
    color: #999;
    font-size: 12px;
  }
}
.paper-mode {
  display: flex;
  margin-bottom: 22px;
  span {
    width: 80px;
    display: block;
    text-align: right;
    color: rgb(96, 98, 102);
    line-height: 40px;
    padding: 0px 12px 0px 0px;
    white-space: nowrap;
    &::before {
      content: "*";
      color: rgb(245, 108, 108);
      margin-right: 4px;
    }
  }
  .mode-radio-group {
    flex: auto;
    display: flex;
    .r-g-radio {
      flex: 1;
      padding: 25px;
      height: 140px;
      border-radius: 6px;
      border-width: 3px;
      border-style: solid;
      cursor: pointer;
      position: relative;
      transition: all 0.1s ease;
      i {
        color: #fff;
        font-size: 16px;
        position: absolute;
        top: 5px;
        right: 3px;
        opacity: 0;
        transition: all 0.1s ease;
      }
      &.active::before {
        content: "";
        display: block;
        width: 0;
        height: 0;
        border-width: 20px;
        border-style: solid;
        border-bottom-color: rgba($color: #000000, $alpha: 0);
        border-left-color: rgba($color: #000000, $alpha: 0);
        position: absolute;
        top: 0;
        right: 0;
        opacity: 0;
        transition: all 0.1s ease;
      }
      &.active {
        i,
        &::before {
          opacity: 1;
        }
      }
      &:first-child {
        margin-right: 20px;
        border-color: rgba(255, 132, 33, 0.1);
        background: rgba(255, 132, 33, 0.1);
        &.active {
          border-color: rgba(255, 132, 33, 1);
          &::before {
            display: block;
            border-top-color: #ff8421;
            border-right-color: #ff8421;
          }
        }
      }
      &:last-child {
        border-color: rgba(69, 90, 247, 0.1);
        background: rgba(69, 90, 247, 0.1);
        &.active {
          border-color: rgba(69, 90, 247, 1);
          &::before {
            display: block;
            border-top-color: #455af7;
            border-right-color: #455af7;
          }
        }
      }
      h4 {
        font-size: 16px;
        line-height: 22px;
        margin-bottom: 10px;
      }
      p {
        color: #77808d;
      }
    }
  }
}
</style>
